import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { USER_API } from '../api/config'

interface UserProfile {
  id: number
  username: string
  nickname: string
  avatarUrl: string
  role: number
  phone: string
  email: string
}

export function useUserProfile() {
  const router = useRouter()
  
  const userProfile = ref<UserProfile>({
    id: 0,
    username: '',
    nickname: '',
    avatarUrl: '',
    role: 0,
    phone: '',
    email: ''
  })

  // 头像表单
  const avatarForm = reactive({
    avatarUrl: ''
  })

  // 个人资料表单
  const profileForm = reactive({
    nickname: '',
    phone: '',
    email: ''
  })

  // 密码表单
  const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })

  // 验证规则
  const profileRules = {
    nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
  }

  const passwordRules = {
    oldPassword: [
      { required: true, message: '请输入当前密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请再次输入新密码', trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (value !== passwordForm.newPassword) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await axios.get(USER_API.PROFILE)
      userProfile.value = {
        id: response.data.id,
        username: response.data.username,
        nickname: response.data.nickname || response.data.username,
        avatarUrl: response.data.avatarUrl || '../assets/homelogo.png',
        role: response.data.role,
        phone: response.data.phone || '',
        email: response.data.email || ''
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败')
    }
  }

  // 更新头像
  const updateAvatar = async () => {
    try {
      if (!avatarForm.avatarUrl.trim()) {
        return ElMessage.warning('请上传头像或输入有效的头像URL')
      }
      
      await axios.put(USER_API.UPDATE_AVATAR, { avatarUrl: avatarForm.avatarUrl })
      userProfile.value.avatarUrl = avatarForm.avatarUrl
      ElMessage.success('头像更新成功')
      return true
    } catch (error) {
      console.error('更新头像失败:', error)
      ElMessage.error('更新头像失败，请稍后重试')
      return false
    }
  }

  // 更新个人资料
  const updateProfile = async () => {
    try {
      await axios.put(USER_API.UPDATE_PROFILE, {
        nickname: profileForm.nickname,
        phone: profileForm.phone,
        email: profileForm.email
      })
      
      userProfile.value.nickname = profileForm.nickname
      userProfile.value.phone = profileForm.phone
      userProfile.value.email = profileForm.email
      
      ElMessage.success('个人资料更新成功')
      return true
    } catch (error) {
      console.error('更新个人资料失败:', error)
      ElMessage.error('更新个人资料失败，请稍后重试')
      return false
    }
  }
  // 更新密码
  const updatePassword = async () => {
    try {
      await axios.put(USER_API.UPDATE_PASSWORD, {
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })
      
      ElMessage.success('密码修改成功，正在为您退出登录...')
      
      // 清除本地存储的用户信息和token
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
      
      // 清除axios默认的Authorization头
      delete axios.defaults.headers.common['Authorization']
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 1500)
      
      return true
    } catch (error) {
      console.error('修改密码失败:', error)
      ElMessage.error('修改密码失败，请确认当前密码是否正确')
      return false
    }
  }

  // 处理头像上传
  const handleAvatarUpload = async (file: File) => {
    if (!file.type.startsWith('image/')) {
      ElMessage.warning('请选择图片文件')
      return false
    }
    
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.warning('图片大小不能超过5MB')
      return false
    }
    
    try {
      const formData = new FormData()
      formData.append('file', file)
      
      const response = await fetch('/api/user/files/upload/image', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formData
      })
      
      if (!response.ok) {
        throw new Error('上传失败')
      }
      
      const data = await response.json()
      avatarForm.avatarUrl = data.fileUrl
      
      ElMessage.success('头像上传成功！')
      return true
    } catch (error: any) {
      console.error('上传失败:', error)
      ElMessage.error(`上传失败: ${error.message || '未知错误'}`)
      return false
    }
  }

  return {
    userProfile,
    avatarForm,
    profileForm,
    passwordForm,
    profileRules,
    passwordRules,
    fetchUserInfo,
    updateAvatar,
    updateProfile,
    updatePassword,
    handleAvatarUpload
  }
}